/*
 * @Author: andy.dell andy@long.com
 * @Date: 2024-01-01 09:24:42
 * @LastEditors: andy.dell andy@long.com
 * @LastEditTime: 2024-01-07 22:05:01
 * @FilePath: \wasm\logic\snake\src\console\control.go
 * @Description:
 */
package console

import (
	"bufio"
	"fmt"
	"os"
	"strings"
	"time"

	"com.game.snake/consts"
	"com.game.snake/model"
	"com.game.snake/service"
)

type handler struct {
	game *service.Game
}

func New(game *service.Game) *handler {
	return &handler{
		game: game,
	}
}

var reader *bufio.Reader

func Play() {
	fmt.Printf("输入 %s 开始游戏~ \n", consts.CMD_START)
	var input = consts.DirectionRight
	reader = bufio.NewReader(os.Stdin)
	input, err := reader.ReadString('\n') // 读取用户输入，直到遇到换行符为止
	if err != nil {
		fmt.Println("读取用户输入发生错误", err)
		return
	}
	for {
		input = strings.TrimSpace(input)
		if input == "" {
			continue
		}
		if input == consts.CMD_START {
			fmt.Println("游戏开始咯...")
			break
		}
		if input == consts.CMD_QUIT {
			fmt.Println("退出游戏...")
			time.Sleep(2 * time.Second) // 休眠2秒
			os.Exit(1)
		}
		fmt.Println("无效输入")
	}
	// 初始化设置
	set := model.NewSetting()
	// 初始化服务
	handler := New(service.New(set))
	go handler.handleInput()
	// 定时更新
	for {
		time.Sleep(1000 * time.Millisecond) // 休眠1秒
		clear()
		// □■
		// ●○
		msg := handler.game.Refresh()
		if msg.IsDead {
			fmt.Println("GAME OVER !!!")
			fmt.Println("输入 q 退出")
			fmt.Println("输入 r 重新开始")
			continue
		}
		handler.rander(msg)
	}
}
